package view.layer
{
	//大厅
	
	import command.LoginCommand;
	
	import event.GlobalEvent;
	
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.system.Security;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	
	import flash3.framework.Layer;
	import flash3.net.INetConnect;
	import flash3.net.MsgPacket;
	import flash3.net.NetFacade;
	
	import global.*;
	import global.Resource;
	
	import libs.bulkloader.BulkProgressEvent;
	import libs.cairngorm.control.CairngormEventDispatcher;
	
	import model.*;
	import model.MeInfoModel;
	
	import net.*;
	
	import util.EffectCharTurnShow;
	import util.IPUtil;
	
	import view.plugin.ChatPanel;
	import view.plugin.FloatText;
	import view.plugin.GlobalPanel;
	import view.plugin.LoaderView;
	import view.plugin.MessageBox;
	import view.plugin.RallyPanel;
	import view.plugin.RechargePanel;
	
	import vo.*;
	
	public class LayerLobby extends Layer
	{
		private var btnGameList:Array;
		private var main:MovieClip;
		private var timer:Timer = null;
		private var loginInfo:LoginInfo;
		private var serverName:TextField = null;
		private var tips:TextField = null;
		private var effectCharTurnShow:EffectCharTurnShow = null;
		
		public function LayerLobby()
		{
			addChild(main = Resource.i.getMovieClip("lobbyBg","LobbyBg"));
			main.y = 75;
			serverName = main.desc.serverName;
			tips = main.desc.tips;
			tips.autoSize = "center";
			createBtn();
			addChild(main);
			timer = new Timer(120000);
			tips.mouseWheelEnabled = false;
			var tf:TextFormat = tips.defaultTextFormat;
			tf.leading = 10.5;
			tips.defaultTextFormat = tf;
			effectCharTurnShow = new EffectCharTurnShow(tips, 6000);
		}
		
		private function createBtn():void
		{
			btnGameList = [];
			var x1:Number = 115; var y1:Number = 192;
			var x2:Number = 320; var y2:Number = 90;
			for(var i:uint = 0; i < 8; i++)
			{
				var mc:MovieClip = Resource.i.getMovieClip("lobbyBtn", "LobbyBtn");
				mc.x = x1 + i % 2 * x2;
				mc.y = y1 + uint(i / 2) * y2;
				main.addChild(mc);
				btnGameList[i] = {mc:mc};
			}
		}
		
		public function onClickBtnGame(evt1:MouseEvent):void
		{
			var obj:Object = null;
			for(var i:uint = 0; i < btnGameList.length; i++)
			{
				obj = btnGameList[i];
				if(obj.mc.btnGame == evt1.target && obj.isOpen && judgeJoinCondition(obj.gameServer))
				{
					GameModel.i.gameServer = obj.gameServer;
					onGameStartHandle();
					break;
				}
			}
		}
		
		public function netRequestLogin(loginRoom:LoginInfo):void
		{
			NetFacade.i.acall(RoomLoginGroup.MDM_GR_LOGON,RoomLoginGroup.SUB_GR_LOGON_SUCCESS,{call:onNetLoginSucceed});
			NetFacade.i.acall(RoomLoginGroup.MDM_GR_LOGON,RoomLoginGroup.SUB_GR_LOGON_FINISH,{call:onNetLoginFinish});
			NetFacade.i.acall(RoomLoginGroup.MDM_GR_LOGON,RoomLoginGroup.SUB_GR_LOGON_ERROR,{call:onNetLoginFailed});
			NetFacade.i.acall(ConfigGroup.MDM_GR_INFO,ConfigGroup.SUB_GR_CONFIG_FINISH,{call:onNetConfigFinish});
			NetFacade.i.addEventListener(Event.CONNECT, onConnectSucceed);
			NetFacade.i.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			NetFacade.i.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			NetFacade.i.addEventListener(Event.CLOSE, onConnectClose);
			LoaderView.i.text = "正在连接服务器，请稍后...";
			Security.loadPolicyFile("xmlsocket://"+loginRoom.dwIP+":"+loginRoom.dwPort);
			NetFacade.i.connect(loginRoom.dwIP, loginRoom.dwPort, new LoginCommand());
			timer.addEventListener(TimerEvent.TIMER, onTimerComplete);
			timer.reset();
			timer.start();
			trace(loginRoom.dwIP, loginRoom.dwPort);
		}
		private function stopTimer():void
		{
			timer.removeEventListener(TimerEvent.TIMER, onTimerComplete);
			timer.stop();
		}
		private function onGameStartHandle():void
		{
			var gameServer:GameServer = GameModel.i.gameServer;
			if(gameServer.isType(GameServer.GAME_GENRE_SCORE))
			{
				loadGameResource();
			}
			else if(gameServer.isType(GameServer.GAME_GENRE_RALLY))
			{
				GameModel.i.poolItem = PrizePoolModel.i.value(gameServer.wServerID);
				RallyPanel.i.updateData();
				RallyPanel.i.show(true);
				RallyPanel.i.addEventListener(RallyPanel.STARTGAME, onClickJoinFace);
			}
			else if(gameServer.isType(GameServer.GAME_GENRE_ANTICHEAT))
			{
				loadGameResource();
			}
		}
		private function onClickJoinFace(evt:Event):void
		{
			var gameServer:GameServer = GameModel.i.gameServer;
			if(MeInfoModel.i.userScore.lGoldScore >= gameServer.dwEnterFee)
			{
				loadGameResource();
			}
			else
				RechargePanel.i.show(true);
		}
		private function onLoginServerHandle():void
		{
			RallyPanel.i.removeEventListener(RallyPanel.STARTGAME, onLoginServerHandle);
			var gameServer:GameServer = GameModel.i.gameServer;
			var loginInfo:LoginInfo = GlobalModel.i.loginInfo;
			loginInfo.dwIP = gameServer.dwServerAddr;
			loginInfo.dwPort = gameServer.wServerPort;
			loginInfo.szPassWord = MeInfoModel.i.mdPassWord;
			loginInfo.loginType = LoginInfo.LOGIN_ROOM_BY_ID;
			loginInfo.dwUserID = MeInfoModel.i.userInfo.dwUserID;
			netRequestLogin(loginInfo);
		}
		private function onConnectSucceed(evt:Event):void
		{
			LoaderView.i.text = "正在验证用户登陆信息...";
			NetFacade.i.send(RoomLoginGroup.MDM_GR_LOGON, RoomLoginGroup.SUB_GR_LOGON_USERID, GlobalModel.i.loginInfo);
		}
		public function onConnectClose(evt:Event):void
		{
			stopTimer();
		}
		public function onIOError(evt:IOErrorEvent):void
		{
			stopTimer();
		}
		public function onSecurityError(evt:SecurityErrorEvent):void
		{
			stopTimer();
		}
		private function onTimerComplete(evt:TimerEvent):void
		{
			stopTimer();
			LoaderView.i.show(false);
			MessageBox.i.show(MessageBox.BTN_OK, "连接超时，请稍后再试！");
		}
		public function onNetLoginSucceed(packet:MsgPacket):void
		{
			
		}
		public function onNetLoginFailed(packet:MsgPacket):void
		{
			onLoginFailed();
		}
		public function onNetLoginFinish(packet:MsgPacket):void
		{
		}
		
		private function onNetConfigFinish(packet:MsgPacket):void
		{
			var gameServer:GameServer = GameModel.i.gameServer;
			if(gameServer.isType(GameServer.GAME_GENRE_SCORE))
			{
				LoaderView.i.text = "正在获取桌子列表...";
				netRequestTableInfo();
			}
			else if(gameServer.isType(GameServer.GAME_GENRE_ANTICHEAT))
			{
				LoaderView.i.show(true);
				LoaderView.i.text = "正在读取场景信息...";
				var userStatus:UserStatusRequest = new UserStatusRequest();
				userStatus.wSiteID = MeInfoModel.i.userStatus.wSiteID;
				userStatus.wTableID = MeInfoModel.i.userStatus.wTableID;
				NetFacade.i.acall(FrameGroup.MDM_GF_FRAME, FrameGroup.SUB_GF_OPTION, {call:netNofityOption});
				NetFacade.i.acall(UserGroup.MDM_GR_USER, UserGroup.SUB_GR_SIT_FAILED, {call:netNofitySitFailed});
				NetFacade.i.acall(CoreGroup.MDM_KN_COMMAND, CoreGroup.SUB_KN_FAILED, {call:netNofitySendFailed, forever:true});
				NetFacade.i.acall(UserGroup.MDM_GR_USER,UserGroup.SUB_GR_USER_MONEY_LESS,{call:onUserMoneyLess});
				NetFacade.i.acall(UserGroup.MDM_GR_USER,UserGroup.SUB_GR_USER_SUPPLY_NEED,{call:onUserSupplyNeed});
				
				//				NetFacade.i.send(UserGroup.MDM_GR_USER, UserGroup.SUB_GR_USER_AUTOSIT_REQ);
				NetFacade.i.send(FrameGroup.MDM_GF_FRAME, FrameGroup.SUB_GF_INFO, false);
				if(gameServer.isType(GameServer.GAME_GENRE_RALLY))
				{
					NetFacade.i.send(UserGroup.MDM_GR_USER, UserGroup.SUB_GR_USER_AGREE_ENTERFEE);
				}
			}
		}
		
		public function netRequestTableInfo():void
		{
			NetFacade.i.acall(TableGroup.MDM_GR_STATUS, TableGroup.SUB_GR_TABLE_INFO, {call:netNofityTableInfo});
			var evt:GlobalEvent = new GlobalEvent(GlobalEvent.GLOBAL_TABLEINFO);
			evt.dispatch();
		}
		private function netNofitySitFailed(...parms):void
		{
			stopTimer();
			LoaderView.i.show(false);
			MessageBox.i.show(MessageBox.BTN_OK, "登陆游戏失败，请稍后再试！");
		}
		private function netNofitySendFailed(...parms):void
		{
			stopTimer();
			LoaderView.i.show(false);
			var packet:MsgPacket = parms[0] as MsgPacket;
			if(packet._id == UserGroup.MDM_GR_USER)
			{
				switch(packet._subid)
				{
					case UserGroup.SUB_GR_USER_AUTOSIT_REQ:
						MessageBox.i.show(MessageBox.BTN_OK, "登陆游戏失败，请稍后再试！");
						break;
					default: break;
				}
			}
		}
		public function onUserMoneyLess(...parms):void
		{
			stopTimer();
			LoaderView.i.show(false);
			NetFacade.i.close();
			RechargePanel.i.show(true);
		}
		public function onUserSupplyNeed(...parms):void
		{
			stopTimer();
			LoaderView.i.show(false);
			NetFacade.i.close();
			RechargePanel.i.show(true);
		}
		private function netNofityTableInfo(...parms):void
		{
			setTimeout(onDelayEnd, 2000);
		}
		
		private function onDelayEnd():void
		{
			stopTimer();
			LoaderView.i.show(false);
			changeState(L.L_SelTable);
		}
		
		private function netNofityOption(...parms):void
		{
			stopTimer();
			LoaderView.i.show(false);
			changeState(L.L_Game);
		}
		
		private function loadGameResource():void
		{
			LoaderView.i.show(true);
			Resource.i.loadModule("game", onLoadGameComplete, onLoadGameProgress);
		}
		
		private function judgeJoinCondition(gameServer:GameServer):Boolean
		{
			return true;
		}
		
		private function onLoginFailed():void
		{
			stopTimer();
			LoaderView.i.show(false);
			MessageBox.i.show(MessageBox.BTN_OK, "登陆失败，请检查用户名和密码！");
		}
		
		override public function enter():void
		{
			var i:uint = 0;
			var mc:MovieClip = null;
			var gameServer:GameServer = null;
			var obj:Object = null;
			var serverCount:uint = GameServerModel.i.length;
			for(i = 0; i < btnGameList.length; i++)
			{
				obj = btnGameList[i];
				mc = obj.mc;
				mc.btnGame.addEventListener(MouseEvent.CLICK, onClickBtnGame);
				
				gameServer = GameServerModel.i.value(i);
				setGameServerData(mc, gameServer);
				
				obj.gameServer = gameServer;
				obj.isOpen = gameServer != null;
			}
			NetFacade.i.close();
			GlobalPanel.i.updateInfo();
			GlobalPanel.i.addEventListener(GlobalPanel.CLICK_LEAVE, onClickBtnLeave);
			
			var tips:Array = ["    拉力赛设置了公共奖池，奖池内奖金随游戏盘数的增加而增加。奖金按排名、汽油拥有量发放，详细规则请点击拉力赛房间查看。把握机会，一夜暴富！"];
			var keys:Array = PrizePoolModel.i.keys();
			var poolItem:MoneyPoolItem = null;
			for(i = 0; i < keys.length; i++)
			{
				poolItem = PrizePoolModel.i.value(keys[i]);
				gameServer = GameServerModel.i.getServer(poolItem.wKindID, poolItem.wServerID);
				if(gameServer)
				{
					tips.push("\n    " + gameServer.szServerName + "中,各奖池奖金已累积至" + poolItem.goldTotal + "金币，请速来领取！\n");
				}
			}
			TableStatusModel.i.clear();
			effectCharTurnShow.text = tips;
			effectCharTurnShow.start();
		}
		
		private function onClickBtnLeave(evt:MouseEvent):void
		{
			
		}
		
		private function setGameServerData(mc:MovieClip, gameServer:GameServer):void
		{
			var isVisible:Boolean = gameServer!=null;
			mc.item1.visible = isVisible;
			mc.item2.visible = isVisible;
			mc.txtNoOpen.visible = !isVisible;
			mc.txtNoOpen.mouseEnabled = false;
			if(gameServer)
			{
				mc.item1.mouseEnabled = false;
				mc.item1.txt1.text = gameServer.szServerName + "  当前"+gameServer.dwOnLineCount+"人";
				//				mc.item1.txt2.text = "当前"+gameServer.dwOnLineCount+"人";
				mc.item1.txt1.mouseEnabled = false;
				//				mc.item1.txt2.mouseEnabled = false;
				mc.item2.mouseEnabled = false;
				mc.item2.mouseChildren = false;
				var isRally:Boolean = gameServer.isType(GameServer.GAME_GENRE_RALLY);
				mc.item2.icon.gotoAndStop(isRally?1:2);
				mc.item2.key.text = isRally?"押金":"底分";
				mc.item2.value.text = isRally?gameServer.dwEnterFee:gameServer.dwCellMoney;
			}
			else
			{
				mc.txtNoOpen.text = "尚未开放";
			}
		}
		
		override public function leave():void
		{
			stopTimer();
			NetFacade.i.rcall(FrameGroup.MDM_GF_FRAME, FrameGroup.SUB_GF_OPTION);
			NetFacade.i.rcall(UserGroup.MDM_GR_USER, UserGroup.SUB_GR_SIT_FAILED);
			NetFacade.i.rcall(CoreGroup.MDM_KN_COMMAND, CoreGroup.SUB_KN_FAILED);
			NetFacade.i.rcall(RoomLoginGroup.MDM_GR_LOGON,RoomLoginGroup.SUB_GR_LOGON_SUCCESS);
			NetFacade.i.rcall(RoomLoginGroup.MDM_GR_LOGON,RoomLoginGroup.SUB_GR_LOGON_FINISH);
			NetFacade.i.rcall(ConfigGroup.MDM_GR_INFO,ConfigGroup.SUB_GR_CONFIG_FINISH);
			GlobalPanel.i.removeEventListener(GlobalPanel.CLICK_LEAVE, onClickBtnLeave);
			effectCharTurnShow.stop();
			LoaderView.i.show(false);
			Resource.i.loadModule("face");
		}
		
		private function onLoadGameProgress(evt:BulkProgressEvent):void
		{
			LoaderView.i.text = "正在加载资源，请稍后...     "+(evt.weightPercent*100).toFixed(0) + "%";
		}
		private function onLoadGameComplete(evt:BulkProgressEvent):void
		{
			onLoginServerHandle();
		}
		
		override public function update(lastTime:int):void
		{
		}
	}
}